package com.bw.counter.adapter

import android.annotation.SuppressLint
import android.widget.CheckBox
import android.widget.TextView
import com.bw.counter.R
import com.bw.counter.entity.ChargeData
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import org.w3c.dom.Text
import java.text.SimpleDateFormat
import java.util.*

class ChargeAdapter : BaseQuickAdapter<ChargeData,BaseViewHolder>(R.layout.item_count_detail) {
    private var isAllSelected = false //全选状态
    var onItemCheckedChangeListener : ((Int,Boolean)->Unit)? = null
    var onAllCheckedChangeListener : ((Boolean)->Unit)?= null

    @SuppressLint("SimpleDateFormat")
    override fun convert(holder: BaseViewHolder, item: ChargeData) {
        val sdf = SimpleDateFormat("yyyy-MM", Locale.getDefault())
        val parse = sdf.parse(item.expirationDate)
        val format = sdf.format(parse)
        holder.getView<TextView>(R.id.time).text = format
        holder.getView<TextView>(R.id.total).text = "￥${item.chargeAmount}"
        holder.getView<TextView>(R.id.tv2).text = item.chargeType
        holder.getView<TextView>(R.id.price1).text = "￥${item.chargeAmount}"
        val sdf2 = SimpleDateFormat("MM/dd", Locale.getDefault())
        val parse2 = sdf.parse(item.effectiveDate)
        val parse3 = sdf.parse(item.expirationDate)
        val s1 = sdf2.format(parse2)
        val s2 = sdf2.format(parse3)
        holder.getView<TextView>(R.id.time2).text = "$s1-$s2"
        val checkBox = holder.getView<CheckBox>(R.id.sel1)
        checkBox.setOnCheckedChangeListener(null)
        checkBox.isChecked = item.isSelected
        checkBox.setOnCheckedChangeListener { compoundButton, b ->
            item.isSelected = b  // 更新状态
            //通知activity 计算总价
            onItemCheckedChangeListener?.invoke(holder.adapterPosition,b)
            updateSelectStatus()
            if (isAllSelected != checkBox.isSelected){
                onAllCheckedChangeListener?.invoke(isAllSelected)
            }
        }
    }



    // 设置全选状态
    fun setAllSelected(selected: Boolean) {
        isAllSelected = selected
        data.forEach { it.isSelected = selected }
        notifyDataSetChanged()
        onAllCheckedChangeListener?.invoke(selected)
    }

    private fun updateSelectStatus() {
        isAllSelected = data.all { it.isSelected }
    }
    //获取全选状态
    fun isAllSelected():Boolean = data.all { it.isSelected }
    fun getSelectTotal():Int{
        return  data.filter { it.isSelected }.sumOf { it.chargeAmount }
    }
}